package leetcode.code2196;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;
import leetcode.helper.tree.TreeNode;

public class Solution implements IDebug {

	public TreeNode createBinaryTree(int[][] descriptions) {
		Set<Integer> root = new HashSet<>();
		Set<Integer> remove = new HashSet<>();
		Map<Integer, TreeNode> map = new HashMap<>();
		for (int[] des : descriptions) {
			int parent = des[0], child = des[1], isLeft = des[2];
			TreeNode parentNode = null;
			if (map.containsKey(parent)) {
				parentNode = map.get(parent);
			} else {
				parentNode = new TreeNode(parent);
				if (!remove.contains(parent))
					root.add(parent);
			}
			TreeNode childNode = null;
			if (map.containsKey(child)) {
				childNode = map.get(child);
				if (root.contains(child)) {
					root.remove(child);
				}
				remove.add(child);
			} else {
				childNode = new TreeNode(child);
			}

			if (isLeft == 1) {
				parentNode.left = childNode;
			} else {
				parentNode.right = childNode;
			}
			map.put(parent, parentNode);
			map.put(child, childNode);
		}
		return map.get(root.iterator().next());
	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
		so.createBinaryTree(HelpDebug.str2array1("[[85,82,1],[74,85,1],[39,70,0],[82,38,1],[74,39,0],[39,13,1]]"));

	}

}
